<template>
  <div>
    <div class="row-header">
      <el-form ref="searchForm" :model="searchForm" :inline="true" label-width="50px" >
        <el-form-item label=" " prop="dictUserType">
          <el-input size="small" placeholder="请输入套餐名字" v-model="searchForm.mealName" style="width: 300px;"></el-input>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="mini" icon="el-icon-search" @click="beforeinitData">查询</el-button>
        <el-button size="mini" type="shenda"   icon="el-icon-refresh-right" @click="resetForm('searchForm')">重置</el-button>
      </div>
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="small" plain @click="cancel" icon="el-icon-back">返回</el-button>
      <el-button type="shenda" size="small" plain @click="beforeinitData" icon="el-icon-refresh" style="margin-right: 5px">刷新数据</el-button>
<!--      <router-link :to="{path: '/road/addMeal',query:{ headId: this.headId, headName: this.headName}}">-->
<!--        <el-button type="shenda" size="small" plain icon="el-icon-plus">添加套餐</el-button>-->
<!--      </router-link>-->
      <router-link :to="{path: '/road/addMeal',query:{ headId: this.headId, headName: this.headName}}">
        <el-button type="shenda" size="small" plain icon="el-icon-plus">添加套餐</el-button>
      </router-link>
<!--      <router-link :to="{path: '/road/addTryPackage',query:{ headId: this.headId, headName: this.headName}}" style="margin-left: 5px">-->
<!--        <el-button type="shenda" size="small" plain icon="el-icon-plus">添加试用套餐</el-button>-->
<!--      </router-link>-->
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="list"
                tooltip-effect="dark" style="width: 100%" v-loading.fullscreen="mainTableLoading"
                element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.2)" class="row-main-table">
        <el-table-column align="center" prop="mealName" key="mealName" label="套餐名称"></el-table-column>
        <el-table-column align="center" prop="dictMealTypeName" key="dictMealTypeName" label="套餐类型"></el-table-column>
        <el-table-column align="center" prop="mealSpec" key="mealSpec" label="套餐规格" ></el-table-column>
        <el-table-column align="center" prop="terOfValidity" key="terOfValidity" label="有效期"></el-table-column>	
		<el-table-column align="center" prop="name" key="name" label="所属组" v-if="headType==1"><template slot-scope="scope">{{ scope.row.name }}</template></el-table-column>		
        <el-table-column align="center" prop="dictSetMealGroupTypeName" key="dictSetMealGroupTypeName" label="套餐组类型" v-if="headType==1"></el-table-column>
        

        <el-table-column align="center" key="state" prop="open" label="开启/隐藏">
          <template slot-scope="scope">
            <el-switch
              active-value="C_YES"
              inactive-value="C_NO"
              v-model="scope.row.dictStatus"
              @change="changePackageStatus($event,scope.row)">
              active-color="#13ce66"
              inactive-color="#999"
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="officialPrice" key="officialPrice" label="官方售价（元）" ></el-table-column>
        <el-table-column align="center" prop="ceilingPrice" key="ceilingPrice" label="代理售价上限" ></el-table-column>
        <el-table-column align="center" prop="oemCostPrice" key="oemCostPrice" label="OEM成本价" ></el-table-column>
        <el-table-column align="center" prop="dictMonthlyPaymentName" key="dictMonthlyPaymentName" label="是否分月到账" v-if="headType==1"></el-table-column>
        <el-table-column align="center" prop="cardFlowImaginary" key="cardFlowImaginary" label="权限值" v-if="headType==1"></el-table-column>
        <el-table-column align="center" prop="seq" label="排序序号"></el-table-column>
        <el-table-column align="center" prop="dictStatusName"  label="使用状态" v-if="headType==1"></el-table-column>
        <el-table-column align="center" prop="dictTerOfValidityName" label="单位" v-if="headType==2"></el-table-column>
        <el-table-column align="center" prop="dictIsPreStorageName" label="是否预存" v-if="headType==2"></el-table-column>
        <el-table-column align="center" prop="thirdId" label="上游套餐编号" v-if="headType==2"></el-table-column>
        <el-table-column align="center" prop="insertTimeTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-button class="operation" style="width: 100%;" @click="editSetMeal(scope.row)">编辑</el-button>
                <el-button class="operation" style="width: 100%;" @click="deleteSetMeal(scope.row)" v-preventReClick>
                  删除
                </el-button>
                <el-button class="operation" style="width: 100%;" @click="updateSeq(scope.row)" v-preventReClick>修改排序
                </el-button>
                <el-button class="operation" style="width: 100%;" @click="updateStatus(scope.row)"
                           v-if="scope.row.dictStatus==='C_YES'&&headType==='1'" v-preventReClick>禁用
                </el-button>
                <el-button class="operation" style="width: 100%;" @click="updateStatus(scope.row)"
                           v-if="scope.row.dictStatus==='C_NO'&&headType==='1'" v-preventReClick>启用
                </el-button>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-size="pagesize"
          :page-sizes="[10,20,50,100]"
          class="row-main-pager"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background>
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {getSetMealList, packageDelete, packageconserve, updateMealStatus} from '@/api/getData'

export default {
  name: "index",
  data() {
    return {
      headId: '',
      headName: '',
      headType: '',
      searchForm: {
        mealName: '',
      },
      list: [],
      pagesize: 10,
      currentPage: 1,
      total: 0,
      mainTableLoading: false,
      open: false,
      ascs: [],
      descs: [],
      limitMb: '',
      limitSpeed: '',
      cardFlowImaginary: '',
    }
  },
  mounted() {
    this.headId = this.$route.query.headerId;
    if (!this.headId) {
      this.$router.push({path: '/road/roadList'})
    }
    this.headName = this.$route.query.headName;
    this.headType = Number(this.$route.query.headType);
    this.initData()
  },
  methods: {
    async initData() {
      this.mainTableLoading = true;
      let returnData = await getSetMealList({
          headId: this.headId,
          mealName: this.searchForm.mealName,
          page: {
            current: this.currentPage + '',
            size: this.pagesize + '',
            ascs: this.ascs,
            descs: this.descs
          }
        },
        {
          obj: this,
          key: 'tableLoading'
        });
      if (returnData._result) {
        this.list = returnData.data.records && returnData.data.records.length > 0 ? returnData.data.records : [];
        for(let item of this.list){
          if(item.mealSpec>=1024){
            item.mealSpec = parseFloat(item.mealSpec/1024).toFixed(2) + ' GB'
          }else{
            item.mealSpec = item.mealSpec + ' MB'
          }
          if(item.dictTerOfValidity==='MONTH'&&item.terOfValidity!=null){
            item.terOfValidity += '个月'
          }
          else if(item.dictTerOfValidity==='DAY'&&item.terOfValidity!=null){
            item.terOfValidity += '天'
          }

        }
        this.total = returnData.data.total;
      }
      this.mainTableLoading = false;
    },
    cancel() {
      this.$router.back(-1)
    },
    beforeinitData() {
      this.currentPage = 1;
      this.initData()
    },
    resetForm() {
      this.searchForm.mealName = '';
    },
    editSetMeal(obj) {
      this.$router.push({path: '/road/addMeal', query: {headId: this.headId, id: obj.id, headName: this.headName}});
      // this.$router.push({path: '/road/add', query: {headId: this.headId, id: obj.id, headName: this.headName}});
    },

    async deleteSetMeal(obj) {
      this.$confirm('您确定要执行此操作么, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let sos = await packageDelete({id: obj.id, headId: this.headId});
        if (sos._result) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.initData();
        }
      }).catch((e) => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    async updateSeq(data) {
      this.pagekey = await this.$getPageKey();
      this.$prompt('请输入排序号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '序号只能为非0正整数',
        inputValue: data.seq
      }).then(async ({value}) => {
        let a = await packageconserve({
          id: data.id,
          seq: value,
          officialPrice: data.officialPrice,
          ceilingPrice: data.ceilingPrice,
          oemCostPrice: data.oemCostPrice,
          limitMb: data.limitMb,
          limitSpeed: data.limitSpeed,
          cardFlowImaginary: data.cardFlowImaginary
        }, {pagekey: this.pagekey});
        if (a._result) {
          this.$message.success("操作成功！");
          setTimeout(async () => {
            this.initData();
            this.pagekey = await this.$getPageKey();
          }, 1000)
        }
      }).catch(() => {
      });
    },
    //翻页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
    },
    handleSizeChange(val){
      this.pagesize = val;
      this.currentPage = 1;
      this.initData();
    },
    updateStatus(row) {
      let tips = row.dictStatus === 'C_YES' ? '您确定要禁用该套餐吗, 是否继续?' : '您确定要启用该套餐吗, 是否继续?';
      this.$confirm(tips, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.saveUpdateStatus(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        });
      });
    },
    //启用 or 禁用
    async saveUpdateStatus(row) {
      let newDictStattus = ''
      let message = ''
      switch (row.dictStatus) {
        case 'C_YES':
          newDictStattus = 'C_NO'
          message = '已禁用套餐'
          break;
        case 'C_NO':
          newDictStattus = 'C_YES'
          message = '已启用套餐'
          break;
      }
      // console.log(row)
      const returnData = await toggleUpdateStatus({
        id: row.id,
        dictStatus: newDictStattus
      });
      if (returnData._result) {
        this.$message.success(message);
        this.initData();
      }
    },
    async changePackageStatus(val,row){
      let status = val=='C_YES'?'开启':'隐藏';
      let pagekey = await this.$getPageKey();
      this.$confirm(`是否立即对当前套餐执行${status}操作？`, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        updateMealStatus({
          id: row.id,
          dictStatus: val,
          pagekey
        }).then(res=>{
          if(res.code==10000){
            this.$message({
              type: 'success',
              message:`当前套餐${status}成功！`
            })
            this.initData()
          }
          else{
            this.$message.error(`当前套餐${status}失败`)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        });
        this.initData()
      });

    },
  }
}
</script>

<style scoped lang="scss">
.el-popper[x-placement^=bottom] {
  margin-right: -31px;
  box-shadow: 0 0 10px #888888;
  margin-left: 6px;

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -31px;

  button {
    display: block;
  }

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}
</style>
